/**
 * @description  : 心跳
 * @descriptionDetail : 心跳-提醒session过期
 * @copyright    : 浙江烟草
 * @author       : mc
 * @create       : 2023-01-01 16:42:50
 */

import hearService from "../service/common/hear.service";
import deviceApi from "../platforms/default.platform.service.js";
import {dateUtils,} from "../common/util";
import store from "../store";

const initHear = () => {
  if(!store.state.needHeartbeat) return -1;
  store.state.hearId = setInterval(verifyTk, 1000 * 60 * 5); // 每5分钟执行一次
};

const clearHear = () => {
  if(store.state.hearId == undefined || store.state.hearId == -1) return;
  try{
    clearInterval(store.state.hearId);
  }catch(e){
    console.log(e);
  }
  store.state.hearId = -1;
};
const tipClose = () => {
  clearHear();
  if(store.state.hearWarnShow) return;
  store.state.hearWarnShow = true;
  uni.showModal({
    title:"提示",
    content:"会话已过期,'确定'将关闭窗口",
    success:(res) => {
      if(res.confirm){
        deviceApi.closeWindow();
      }
    },
    complete:(coe) => {
      store.state.hearWarnShow = false;
    },
  });
};

const verifyTk = () => {
  console.log('进来了');
  hearService.verifyTk().then(res => {
    let second = res.bean || 0;
    if(second <= 60 * 5 && second > 0) { // 小于一次循环的时间
      store.state.hearWarnShow = true;
      let str = "";
      if(res.bean / 60 >= 1){
        str = `${Math.trunc(res.bean / 60)}分`;
      }
      str = `${str}${res.bean % 60}秒`;
      uni.showModal({
        title: "提示",
        content:`会话将在${str}后过期\n提示时间:${dateUtils.dateFormat('yyyy-MM-dd HH:mm:ss',new Date())}\n点击'确定'可续期\n#注意超时续期无效`,
        success: (rep) => {
          if (rep.confirm) {
            console.log('用户点击确定');
            hearService.currentAccount().then(rpp => {
              if(rpp.code != 200){ // 表示会话已过期
                tipClose();
              }
            }).catch(epp => {
              console.log(epp);
              tipClose();
            });
          } else if (rep.cancel) {
            console.log('用户点击取消');
          }
        },
        complete:(rp) => {
          console.log('都会结束',rp);
          store.state.hearWarnShow = false;
        },
      });
    }else if(second <= 0){ // 会话已过期
      tipClose();
    }
  }).catch(e => {
    console.log("错误",e);
  })
};

export default{initHear,};
